package com.my.interview.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Socket 服务端， 基于SocketServer
 */
public class MyServerSocket {

    public static void main(String[] args) {


        try{

            //创建一个ServerSocket监听8089端口
            ServerSocket serverSocket = new ServerSocket(8089);
            //等待请求
            Socket socket = serverSocket.accept();
            //接收到请求后使用Socket进行通信，使用BufferReader读取数据
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String line = bufferedReader.readLine();
            System.out.println("received from client : " + line);
            //发送数据
            PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
            printWriter.print("receive data: " + line);
            printWriter.flush();
            //关闭资源
            printWriter.close();
            bufferedReader.close();
            socket.close();
            serverSocket.close();

        }catch (IOException e){
            e.printStackTrace();
        }

    }
}
